# Copyright (c) 2025 Bytedance Ltd. and/or its affiliates
# SPDX-License-Identifier: MIT

"""
Entry point script for the DeerFlow project.
"""

import argparse
import asyncio

from InquirerPy import inquirer

from src.config.questions import BUILT_IN_QUESTIONS, BUILT_IN_QUESTIONS_ZH_CN
from src.workflow import run_agent_workflow_async


def ask(
    question,
    debug=False,
    max_plan_iterations=1,
    max_step_num=3,
    enable_background_investigation=True,
    output_md=None,
    output_pdf=None,
):
    """Run the agent workflow with the given question.

    Args:
        question: The user's query or request
        debug: If True, enables debug level logging
        max_plan_iterations: Maximum number of plan iterations
        max_step_num: Maximum number of steps in a plan
        enable_background_investigation: If True, performs web search before planning to enhance context
        output_md: Path to save markdown file
        output_pdf: Path to save PDF file
    """
    asyncio.run(
        run_agent_workflow_async(
            user_input=question,
            debug=debug,
            max_plan_iterations=max_plan_iterations,
            max_step_num=max_step_num,
            enable_background_investigation=enable_background_investigation,
            output_md=output_md,
            output_pdf=output_pdf,
        )
    )


def main(
    debug=False,
    max_plan_iterations=1,
    max_step_num=3,
    enable_background_investigation=True,
):
    """Interactive mode with built-in questions.

    Args:
        enable_background_investigation: If True, performs web search before planning to enhance context
        debug: If True, enables debug level logging
        max_plan_iterations: Maximum number of plan iterations
        max_step_num: Maximum number of steps in a plan
    """
    # First select language
    language = inquirer.select(
        message="Select language / 选择语言:",
        choices=["English", "中文"],
    ).execute()

    # Choose questions based on language
    questions = (
        BUILT_IN_QUESTIONS if language == "English" else BUILT_IN_QUESTIONS_ZH_CN
    )
    ask_own_option = (
        "[Ask my own question]" if language == "English" else "[自定义问题]"
    )

    # Select a question
    initial_question = inquirer.select(
        message=(
            "What do you want to know?" if language == "English" else "您想了解什么?"
        ),
        choices=[ask_own_option] + questions,
    ).execute()

    if initial_question == ask_own_option:
        initial_question = inquirer.text(
            message=(
                "What do you want to know?"
                if language == "English"
                else "您想了解什么?"
            ),
        ).execute()

    # Pass all parameters to ask function
    ask(
        question=initial_question,
        debug=debug,
        max_plan_iterations=max_plan_iterations,
        max_step_num=max_step_num,
        enable_background_investigation=enable_background_investigation,
    )


rule = '''
你是一位创业导师，CEO，投资人，擅长分析创业案例，并从中获得启发。
你将收到一篇关于获得财富成功的案例。普通人希望从中获得启发，获得类似成功。

请深入分析案例，给出详细报告：
- 案例解决的问题
- 市面上已有的代表性解决方案，包括但不限于：
    - 各个方案工作原理，图文介绍，网址，服务名称，视频链接
    - 优缺点
    - 表格形式总结以上信息
- 案例的解决方案
    - 使用的方法，步骤
    - 面临的挑战，如何克服。使用的外部工具，服务，花费的时间等资源投入
- 案例获得的效果：包括但不限于月收入，利润，用户数
- 案例可能存在，包括但不限于，以下问题：
    - 夸大宣传。
    - 缺乏具体指导。
    - 需要特殊的资源，不适合普通人。
    - 过时，市场发生变化，文中方法不再适用。
- 改进方案

对每个论点给出论据，参考文献，使得内容充实饱满，有说服力。
报告使用中文，以markdown文本格式输出。
文风流畅，引人入胜，足够吸引流量。
'''

case_story = '''
This is dawson and he built a million dollar per year crypto APP all by himself. And the crazy part is he built it in less than a day. I basically went start to finish, I think four or five hours total. He invited us into his van home in Colorado to show us exactly how we built this thing. And the viral marketing strategy that got him ten zero organic signups in just forty eight hours. What I really leaned into was but there was a problem. All of those users didn't pay him a single dollar. Then dawson came up with a genius monetization strategy that scaled him to over one hundred thousand dollars a month. Yeah, so I came up with this idea of an anti email strategy. In this video, dawson will share the exact ideation, marketing and monetization blueprints he used to build a one million dollar APP as a solo developer. I'm pat walls and this is starter story.Dawson thanks for having me. We're in your sprinter van right now in boulder, Colorado. Tell me about who you are and what you built. Yeah, of course. Thanks for having me. My name is dawson. I am a solo pneur software engineer. I made a company called unifi and unifi helps ethereum users find and claim money they didn't know they had. I grew utified to over two hundred and fifty zero free users, five zero paid users and that was over a million dollars ARR. And then had a liquidity event, took my exit and moved into this van doing a little exploring, doing a little consulting, but mostly just skiing. Nice. Tell me a little bit more about earnify this web three startup that you built. If you're a user of ethereum, you're going all over the place investing in things, trading, swapping, voting and governance. But you don't know about these things called airdrops. Now airdrops are like coupons. It's like ah hey, come use this thing we'LL give you an airdrop free money honestly. So earnif five is just a very simple website. If you put in your thereem address on the homepage you're going to get instant results.Of what are your unclaimed airdrops? And it's very common to get hundreds or thousands of dollars in these if you're even moderately active in ethereum, the average user over the course of the entire website was getting seven hundred and fifty dollars by being a customer, right? Let's talk about your backstory. What were you doing that led you to starting this amazing business? Really when I was a kid, I was I was really into video games and I was really into just being a dork honestly with math and science, and that really paid out well in middle school. I had a friend who taught me how to start programming. I wrote these programs that actually helped us cheat on our geometry tests. People started plugging in and sharing the program. That was my first taste of, you know, like product market fit and having people like the thing you code or build. But that path was not very straightforward for me. So when I was a student I actually lost a lot of interest in software, the dig. Found a way to kind of take the excitement away for me after my first two years. I I wanted to drop out but instead of dropping out I got a taste of hackathons. Hackathons I think are so fun because it gives you the opportunity not just to create something fast but also you can build products that real people use. You can build things that real people want. If you do it right you can put it on a website and have real users at the end of the weekend. Yeah and I was addicted from then on really on ah understanding that software could go change the world. Yeah, so you were working as software engineer at Uber and some other big Tech healthcare companies. What was that experience like? Yeah, working at a company like Uber, obviously the salary is pretty lucrative from the outside. It's a booming successful startup. I was there in twenty sixteen, I was there pre IPO. That was the hot place to be. And yet while there I just saw the downsides of large corporations, just ineffective teams, honestly, and that was a bit sad to be a part of because I really want to make direct change in this world. And so in addition to just being a disillusioned with big Tech, then I was also disillusioned with kind of the office space.And just not wanting to show up every day, I needed to get a break and get away. So what I did actually is I left and I just no matterded, I just traveled the world for a year and I I almost just had to reach the point of like I don't need software for now, you know, it's gonna to be a nomad, I'm just gonna to travel and and do yoga and see the world. You know what was that experience like of deciding to quit and and drop everything and and go do this nomad thing. How did you feel in that time? Yeah, so I felt really scared. I felt really worried to kind of step out of that comfort. This was a pretty risky move to leave not just a great startup but also to leave SAN Francisco. I felt like all of software existed there, but during that year of travel I met some folks in Australia who were distributing financial aid for nonprofits through ethereum, and it was just the most niche out of this world experience to cross paths with those folks while being outside of SAN Francisco and, and outside of the Tech bubble. They almost like pulled me back in to realize technology can be used for good, technology can be impactful and that got me really interested all over again and in software in ethereum.And making something in crypto. Yeah, what happens next? How do you come up with the idea for earn a I? When I came back to the us s it took me over a year to kind of reassimilate to being in the us s, being American and knowing that I wanted to base my life here as I did that, I just started competing in more and more of these hackathons. This was a one month long hackathon and crypto was popping off. It was getting very hot. As a user in this community I knew the pain points. I already knew which problem I wanted to solve, but I love waiting until the ideas are really clear. And so sometimes I'LL take the first two or three weeks of a month long hackathon just letting the ideas bounce around in my brain, so that when I do hit the computer, I have tons of conviction. Once I had that conviction, the idea just flows a lot more easily. And that's what happened here is that I waited till, till almost the last second, from then it was just building. Solution I needed once I hit the hit the codebase and started writing this I basically went start to finish I think four or five hours total. Dawson is proof that just one person can start a million dollar business in just a few hours, but that comes with knowing the right information and finding the right problem to solve. Now imagine there was a place that gave you all this, the problems to solve, the blueprints to solve them and the strategies that turn simple ideas into million dollar online businesses. Well at starter story, we have a library of over four zero case studies and business idea breakdowns where you can access this all backed by data from real entrepreneurs. So if you're serious about building a profitable side project, head to the first link in the description and we're going to give you 50 solo developer ideas, just like dawson's so you can get started on your journey. Now let's get back to how dawson actually launched this business peace. So you build this thing and basically.Five hours in the hackathon and it starts taking off. Can you tell me more about that? Yeah, I shipped the website, put it on a public URL and publishing this tweet that just went super viral about the website crafted this tweet just really intentionally. I included a nice little video of how the the searching worked for an address that had a ton of airdrops for it. So of course it's kind of teasing folks, letting them know this is what's possible out there and I think there's almost a bit of a charitable feeling where folks were like, I want to help other people find the money they didn't know they had. Also hitting re to was such an easy thing to DOI had ten zero organic signups at the end of that 48 hours and how did you get those signups? Yes, I got those signups by optimizing this page for the call to actions to sign up for the email, both in the header and in just a massive button above the fold, using drop shadows and borders properly to draw the user's eyes towards these buttons it felt incredible I almost was was losing faith before that is, you know I've always been shipping stuff but never had that many eyes on what I've what I've built yeah, I thought you had to be already at the top to get eyes on your your content but I realized if you just add.Lot of value for people that you can rise to the top that way as well. Yeah, so you got this APP, it's getting a bunch of free users, how does this turn into a thing that makes a million dollars? ARR I came up with this idea of an anti email strategy, and this is just rooting from the fact that I hate getting spam emails and so I just never sent an email unless the email was, you have matched this amount of money, you had this to go claim the open rate was through the roof, just everyone wanted to always open these emails if they got one, and then what I just did is I decided one day every single airdrop from now on is going to be paywalled so you'll see, okay, you have 793 dollars of this airdrop, but you cannot claim it unless you pay yeah, if I was charging people, it was always so they could get even more out of it and I felt like that honest relationship. To so many sign ups and just people telling other friends about it as well. Yeah let's talk about growth. What channels actually grew this business? Yes, SOA strict choice I made in the beginning was never do paid ads. By doing that, anyone that even hears about the website already knows that they have money to go claim there, but what I really leaned into was Twitter. SOA lot of crypto people hang out on Twitter and I used to do these really kitschy fun campaigns where I did one called 25 days of Christmas. Every single day for 25 days I would tag someone publicly on Twitter and say the amount of dollars they had unclaimed with a screenshot. It was basically saying like you're an idiot if you don't go claim this and they would be tagging them and all that. Yeah, even there'd be this community pressure that was actually healthy yeah of other people seeinging it being like well, I wish I had that to go claim yeah I also just became a fiend for going to conferences, showing up in person and letting people know about what I was building led to even more signups as well. Cool. But yeah, crypto is a crowded space. Anyone could build an APP like this technically how did you differentiate utfi? The thing that made utfi so different is just how obsessive I was about cool.Quality and that led to this really good reputation again where if someone got a notification, they knew it was a high dollar value that they could go claim right then and any the competitors who were trying, they were including too much, not too much led to lower quality and then people didn't trust and trust is so big because of how much hacking and phishing there is within crypto. Yeah another part is just being early. That's not always advice you can replicate but if you can that's obviously going to be helpful. You can be the first to the scene and then provide so much quality that no one can even catch up. Yeah so you built this as a solo developer, as a solo panneur. Tell me what that experience was like? Yeah, solo has a lot of pros and a lot of cons. One of the pros is you get to take it where you want. You don't have to ask permission and you get to ship to users directly. Any team is going to slow you down a bit on that, but of course the cons are it can be lonely. You can also think something's a great idea when it's not, and so you got to stay around in communities if you can. I did a bit of Co workinging at the time, and these conferences I mentioned in order to bounce off ideas from other people and make sure I wasn't just in an echo chamber in my head, yeah, you're a software engineer, what are your favorite tools and.Languages, what do you build with? Yeah, finally the best part. So what I love to code in is typescript. I use typescript full stack. We've got nodejs on the back end, we've got react on the front end and pull this all together with a framework called nextjs. So nextjs makes really fast websites having speed and having all of this website just load so fast for everyone was also part of what helped me grow. I'm a big Mac guy, I have a maxed out MacBook pro, I have a split keyboard, just super nerdy, I can get good posture and just a huge thirty two thirty one inch monitor to make sure that my eyes are resting all day as well. For code edit I use vscode. Anyone out there who does typescript knows that's probably going to be the best choice anyways. So you got this successful profitable business and then something crazy. Happens. Can you tell me about that? So I got a Twitter DM from from David Hoffman. He's one of the podcasters in this large podcast called banklesss. I had been watching and listening to banklesss for years. In fact, bankless helped me get into ethereum. I had a bucket list item that was to get my name mentioned on banklesss. Not only did I get my name mentioned but I ended up being the CTO and so it was just a dream come true. But I never considered the acquisition route until they reached out and I realized how realistic that was. We talked for several months about some of the specifics and yeah, after two years of growing the company alone, it was acquired by banklesss. You sell your company, you have this life changing event. Tell me what that experience was like. Yeah, I felt like there was a huge celebration but then right after that kind of wears off, the dopamine wears off a bit of a free fall feeling. This used to be your passion. It used to be how you spend every day and then after that you've got to discover what your new meaning is going to be. I fill that a bit with with travel, with fitness, with skiing, with this van. When you say that it sounds like the dream. Oh of course I want to ski seven days a week. Of course I want to go wherever I want whenever I want but.Actually that's not the dream. It only took me a couple weeks to really feel how dark that could be because yeah you can ski every day, but what you're spending seven days alone up in the mountains, you're not sharing experiences with other people and it turns out a lot of my meaning is through community company or doing work, or are you working now? I do, yeah so I see myself as a serial entrepreneur. This is just one of hopefully many and at the moment I have started some consulting I'm really doing a lot of open source projects as well. Back on Twitter again I'm also on far caster, which is this website that is a decentralized social media platform and so just publishing and building in public is, is already what I've started doing again. All right well you're living this van life right now. Tell me what a day in the life like is for you living out this van working and skiing. Yeah a day in the life is you know, I manage spending time with friends and I manage spending time up in the mountains and I manage a little bit of time on the computer. So I kind of balance these three things. Besides that I spend a lot of time at either Co workinging spaces, putting myself around other people, or going to these meetups making sure I'm still around these ideas a lot, but really doing.From a different place mentally because I want to, I'm doing it for the fun of it. I'm not doing it because I have to find customers or I have to find that next idea necessarily. Yeah, that's great. Okay, one final question. If you could sit on dawson's shoulder when you were, you know, a software engineer at Uber kind of really trying to figure out what you wanted to do when you're a digital nomad, what advice would you have for him? Yeah, if I were to talk to my old self, I think I would just say enjoy the process more. I wouldn't want to change what got me to today. Anything that seems like a misstep was actually something that taught me a lot but it's just that during that process don't have as much anxiety, don't have as much worry because it will all work out. You know like look at me now it's panned out pretty well. All right man. Well thank you. Thank you for having. Us follow this advice and you'll build a million dollar ethereum airdrop APP hey guys, pat here. I really hope dawson's story inspires you and motivates some of you to go ahead and start your own thing. If you're curious about doing something similar but you're still looking for an idea, well I have something for you right now you can download our deep dive solo developer report for free. It breaks down 50 different solo developer ideas including their business models, how much money they make and tons of other stuff you'd want to know! Just click the first link in the description and if you're serious about finally building your own idea, consider joining starter story and we'll help you do that! Much love, I'll see you guys in the next one! Peace!
'''

query = f'''
```rule
{rule}
```

```case
{case_story}
```
'''

if __name__ == "__main__":
    # Set up argument parser
    parser = argparse.ArgumentParser(description="Run the Deer")
    parser.add_argument("query", nargs="*", help="The query to process")
    parser.add_argument(
        "--interactive",
        action="store_true",
        help="Run in interactive mode with built-in questions",
    )
    parser.add_argument(
        "--max_plan_iterations",
        type=int,
        default=1,
        help="Maximum number of plan iterations (default: 1)",
    )
    parser.add_argument(
        "--max_step_num",
        type=int,
        default=2,
        help="Maximum number of steps in a plan (default: 3)",
    )
    parser.add_argument("--debug", action="store_true", help="Enable debug logging")
    parser.add_argument(
        "--no-background-investigation",
        action="store_false",
        dest="enable_background_investigation",
        help="Disable background investigation before planning",
    )
    parser.add_argument(
        "--output-md",
        type=str,
        default="results/report.md",
        help="Save the report as a Markdown file to the specified path",
    )
    parser.add_argument(
        "--output-pdf",
        type=str,
        default="results/report.pdf",
        help="Save the report as a PDF file to the specified path",
    )

    args = parser.parse_args()

    if args.interactive:
        # Pass command line arguments to main function
        main(
            debug=args.debug,
            max_plan_iterations=args.max_plan_iterations,
            max_step_num=args.max_step_num,
            enable_background_investigation=args.enable_background_investigation,
        )
    else:
        # Parse user input from command line arguments or user input
        if args.query:
            user_query = " ".join(args.query)
        else:
            # user_query = input("Enter your query: ")
            user_query = query

        # Run the agent workflow with the provided parameters
        ask(
            question=user_query,
            debug=args.debug,
            max_plan_iterations=args.max_plan_iterations,
            max_step_num=args.max_step_num,
            enable_background_investigation=args.enable_background_investigation,
            output_md=args.output_md,
            output_pdf=args.output_pdf,
        )
